﻿using System;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;

namespace IoTSignalR
{
    //单向通信，要实现半双工通信
    public class AnonymousPipeClient
    {      
        //读写
        private AnonymousPipeClientStream anonymousPipeClientStreamReader;
        private AnonymousPipeClientStream anonymousPipeClientStreamWriter;
        private readonly string handleReader;
        private readonly string handleWriter;

        public event EventHandler<string> SendMessageEvent;
        public event EventHandler<string> ReceiveMessageEvent;
        public AnonymousPipeClient(string handleReader,string handleWriter)
        {
            this.handleReader = handleReader;
            this.handleWriter = handleWriter;
        }
        public async Task StartAsync()
        {
            anonymousPipeClientStreamReader = new AnonymousPipeClientStream(PipeDirection.In, handleReader);
            anonymousPipeClientStreamWriter = new AnonymousPipeClientStream(PipeDirection.Out, handleWriter);
            try
            {
                SendMessageEvent += async (sender, msg) =>
                {
                    byte[] messageBytes = Encoding.UTF8.GetBytes(msg);
                    await anonymousPipeClientStreamWriter.WriteAsync(messageBytes, 0, messageBytes.Length);
                    await anonymousPipeClientStreamWriter.FlushAsync();
                };
                _ = Task.Run(async () => await ReceiveMessage());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }

        private async Task ReceiveMessage()
        {
            byte[] bufferBack = new byte[1024];
            while (true)
            {
                int bytesRead = await anonymousPipeClientStreamReader.ReadAsync(bufferBack, 0, bufferBack.Length);
                if (bytesRead > 0)
                {
                    string serverMsg = Encoding.UTF8.GetString(bufferBack, 0, bytesRead);
                    ReceiveMessageEvent.Invoke(this, serverMsg);
                }
            }
        }
        public void SendMsg(string msg)
        {
            SendMessageEvent.Invoke(this, msg);
        }
    }
}
